global root_dir = "`1'"

include "$root_dir/code/config/config.do"


cap noi log using ${log_dir}/spillovers.log, replace name(dat)

*Handle empty arguments
global arg1 = cond("`2'" == "___EMPTY___", "", "`2'")
global arg2 = cond("`3'" == "___EMPTY___", "", "`3'")
global arg3 = cond("`4'" == "___EMPTY___", "", "`4'")
global arg4 = cond("`5'" == "___EMPTY___", "", "`5'")

if "$arg1" != "" {
    global weight_category "$arg1"
    di "Weight category: ${weight_category}"
}

if "$arg2" != "" {
    global weight_versions "$arg2"
    di "Weight versions: ${weight_versions}"
}

if "$arg3" != "" {
    global weight_window "$arg3"
    di "Weight window: ${weight_window}"
}

if "$arg4" != "" {
	global wtype "$arg4"
}
di "${wtype}"

capture noi {



/* This do-file builds the spillover variables for the different technologies, 
multiplying the innovation stocks with the firm-level country of invention weights */

* Set maxvar
clear
set maxvar 32767

* Load country list
do ${code_dir}/config/country_list.do

cap program drop make_spillover
program make_spillover
	local xxx `1'
	local ttt `2'

	*get the lsit with all firms used anywhere for any window (see bvd_year_lists.do)
	use ${dataset_dir}/dep_vars/bvd_year_list_any_any.dta, clear
	* Add country-level invention stocks
	mmerge year using ${dataset_dir}/spillovers/ctry_inventions_stocks_wide_`ttt', unmatched(master) ukeep(k`ttt'_`xxx'* k`ttt'_N_`xxx'*)
	* weights based on 10-years patent portfolio pre-1980, etc
	mmerge BvD using ${dataset_dir}/weights/bvdid_inventor_weights_all_from1970_1995_orbis2017, unmatched(master) 
	gen missing_spill_weights_1995=(_m==1)
	drop _m

	* merge in average shares (for companies that have 0 patent pre-sample) ->WD
	cross using ${dataset_dir}/weights/shares_INV_allctries_alltechs_1995.dta
	sort BvD year

	* do this for all techs and their NOT tech complements
	foreach vv in `xxx' N_`xxx' {
		foreach ctry in $invtcountrylist{
			noisily capture confirm variable share_WD_total_inv_`ctry'
			if _rc != 0 {
				*if a firm-country combination has no share, we assume it did not have any inventions in that year
				*fairly reasonable, as we have a very complete set of patents
				gen share_WD_total_inv_`ctry' = 0
			}

			*generate a weighted spillover variable (share_invt_1995_`ctry' is at the firm-country level; the stocks (k) at the country level)
			gen k`ttt'`vv'_wtd_`ctry' = share_invt_1995_`ctry' * k`ttt'_`vv'_`ctry'
			*same for average shares
			gen k`ttt'`vv'_wtd_WD_`ctry' = share_WD_total_inv_`ctry' * k`ttt'_`vv'_`ctry'
		}
	}
	*again, for all techs and their NOT tech complements
	foreach vv in `xxx' N_`xxx'{

		*collect all spillovers obtained for a firm in a given year average shares
		egen spill_`vv'_`ttt'_WD_1995=rowtotal(k`ttt'`vv'_wtd_WD_??), missing
		*same for the normal ones
		egen spill_`vv'_`ttt'_1995_wtd = rowtotal(k`ttt'`vv'_wtd_??), missing

		*replace if we have missing weights using the average shares
		replace spill_`vv'_`ttt'_1995_wtd = spill_`vv'_`ttt'_WD_1995 if spill_`vv'_`ttt'_1995_wtd==.
	}

	*genearte indicators if we have zero spillovers (for the logs and for the regressions)
	*generate logs and correct for zeros
	drop *wtd_* share* *WD*
	gen spill`xxx'`ttt'_1995_a0 = spill_`xxx'_`ttt'_1995_wtd==0
	gen spillN`xxx'`ttt'_1995_a0 = spill_N_`xxx'_`ttt'_1995_wtd==0
	gen spill`xxx'`ttt'_1995_a = log(spill_`xxx'_`ttt'_1995_wtd)
	gen spillN`xxx'`ttt'_1995_a = log(spill_N_`xxx'_`ttt'_1995_wtd)
	replace spill`xxx'`ttt'_1995_a = 0 if spill`xxx'`ttt'_1995_a0 == 1
	replace spillN`xxx'`ttt'_1995_a = 0 if spillN`xxx'`ttt'_1995_a0 == 1
	
	drop spill_`xxx'_`ttt'_1995_wtd spill_N_`xxx'_`ttt'_1995_wtd
	drop k`ttt'*

	*labeling

	compress
	save ${dataset_dir}/spillovers/bvd_year_spillovers_`xxx'_`ttt'.dta, replace
end

*running over all biadic technologies
foreach xxx in auto80 auto90 auto95 autoX95 autonol95 pauto90 pauto95 pauto90_rm6 CNC80 CNC90 CNC95 robo80 robo90 robo95 autm80 autm90 autm95 tfa {
	make_spillover `xxx' bia
}


}
if _rc == 0 {
    display "Execution finished successfully."
}
else {
    display "Execution finished with errors."
}

cap log close dat